/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package o2uz;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import o2uz.exceptions.IllegalOrphanException;
import o2uz.exceptions.NonexistentEntityException;

/**
 *
 * @author tomcat
 */
public class FacultyJpaController implements Serializable {

    public FacultyJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Faculty faculty) {
        if (faculty.getInstituteCollection() == null) {
            faculty.setInstituteCollection(new ArrayList<Institute>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Institute> attachedInstituteCollection = new ArrayList<Institute>();
            for (Institute instituteCollectionInstituteToAttach : faculty.getInstituteCollection()) {
                instituteCollectionInstituteToAttach = em.getReference(instituteCollectionInstituteToAttach.getClass(), instituteCollectionInstituteToAttach.getIdInstitute());
                attachedInstituteCollection.add(instituteCollectionInstituteToAttach);
            }
            faculty.setInstituteCollection(attachedInstituteCollection);
            em.persist(faculty);
            for (Institute instituteCollectionInstitute : faculty.getInstituteCollection()) {
                Faculty oldFkFacultyOfInstituteCollectionInstitute = instituteCollectionInstitute.getFkFaculty();
                instituteCollectionInstitute.setFkFaculty(faculty);
                instituteCollectionInstitute = em.merge(instituteCollectionInstitute);
                if (oldFkFacultyOfInstituteCollectionInstitute != null) {
                    oldFkFacultyOfInstituteCollectionInstitute.getInstituteCollection().remove(instituteCollectionInstitute);
                    oldFkFacultyOfInstituteCollectionInstitute = em.merge(oldFkFacultyOfInstituteCollectionInstitute);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Faculty faculty) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Faculty persistentFaculty = em.find(Faculty.class, faculty.getIdFaculty());
            Collection<Institute> instituteCollectionOld = persistentFaculty.getInstituteCollection();
            Collection<Institute> instituteCollectionNew = faculty.getInstituteCollection();
            List<String> illegalOrphanMessages = null;
            for (Institute instituteCollectionOldInstitute : instituteCollectionOld) {
                if (!instituteCollectionNew.contains(instituteCollectionOldInstitute)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Institute " + instituteCollectionOldInstitute + " since its fkFaculty field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Institute> attachedInstituteCollectionNew = new ArrayList<Institute>();
            for (Institute instituteCollectionNewInstituteToAttach : instituteCollectionNew) {
                instituteCollectionNewInstituteToAttach = em.getReference(instituteCollectionNewInstituteToAttach.getClass(), instituteCollectionNewInstituteToAttach.getIdInstitute());
                attachedInstituteCollectionNew.add(instituteCollectionNewInstituteToAttach);
            }
            instituteCollectionNew = attachedInstituteCollectionNew;
            faculty.setInstituteCollection(instituteCollectionNew);
            faculty = em.merge(faculty);
            for (Institute instituteCollectionNewInstitute : instituteCollectionNew) {
                if (!instituteCollectionOld.contains(instituteCollectionNewInstitute)) {
                    Faculty oldFkFacultyOfInstituteCollectionNewInstitute = instituteCollectionNewInstitute.getFkFaculty();
                    instituteCollectionNewInstitute.setFkFaculty(faculty);
                    instituteCollectionNewInstitute = em.merge(instituteCollectionNewInstitute);
                    if (oldFkFacultyOfInstituteCollectionNewInstitute != null && !oldFkFacultyOfInstituteCollectionNewInstitute.equals(faculty)) {
                        oldFkFacultyOfInstituteCollectionNewInstitute.getInstituteCollection().remove(instituteCollectionNewInstitute);
                        oldFkFacultyOfInstituteCollectionNewInstitute = em.merge(oldFkFacultyOfInstituteCollectionNewInstitute);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = faculty.getIdFaculty();
                if (findFaculty(id) == null) {
                    throw new NonexistentEntityException("The faculty with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Faculty faculty;
            try {
                faculty = em.getReference(Faculty.class, id);
                faculty.getIdFaculty();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The faculty with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Institute> instituteCollectionOrphanCheck = faculty.getInstituteCollection();
            for (Institute instituteCollectionOrphanCheckInstitute : instituteCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Faculty (" + faculty + ") cannot be destroyed since the Institute " + instituteCollectionOrphanCheckInstitute + " in its instituteCollection field has a non-nullable fkFaculty field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(faculty);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Faculty> findFacultyEntities() {
        return findFacultyEntities(true, -1, -1);
    }

    public List<Faculty> findFacultyEntities(int maxResults, int firstResult) {
        return findFacultyEntities(false, maxResults, firstResult);
    }

    private List<Faculty> findFacultyEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Faculty.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Faculty findFaculty(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Faculty.class, id);
        } finally {
            em.close();
        }
    }

    public int getFacultyCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Faculty> rt = cq.from(Faculty.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
